package com.cpecc.controller.system;

import com.cpecc.mail.SendMailThread;
import com.cpecc.manager.system.EmailManager;
import com.cpecc.manager.system.RootManager;
import com.cpecc.manager.system.UserManager;
import com.cpecc.manager.system.YouJianManager;
import com.cpecc.model.system.Email;
import com.cpecc.model.system.User;
import com.cpecc.model.system.YouJian;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping(value = "/system")
public class LoginController {
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private EmailManager emailManager;
	
	@Autowired
	private RootManager rootManager;
	
	@Autowired
	private YouJianManager youJianManager;
	
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(User user,HttpSession session, HttpServletRequest request) {		
		ModelAndView mav = new ModelAndView();
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
		token.setRememberMe(false);
		try {
			currentUser.login(token);
		} catch (UnknownAccountException uae) {
			mav.addObject("message", "用户名密码错误!");			
		} catch (IncorrectCredentialsException ice) {
			mav.addObject("message", "用户名密码错误!");			
		} catch (LockedAccountException lae) {
			mav.addObject("message", "账户被锁定!");			
		} catch (ExcessiveAttemptsException eae) {
			mav.addObject("message", "认证失败!");			
		} catch (AuthenticationException ae) {
			mav.addObject("message", "登录失败!");			
		}
		if(currentUser.isAuthenticated()){
			if(userManager.findByUsername(user.getUserName()).isLocked()){
				mav.addObject("message", "账户被锁定!");
				mav.setViewName("redirect:/login.jsp");
			}else if(userManager.findByUsername(user.getUserName()).getDep().getId().equals("888888")){
				mav.addObject("message", "未定义部门，请联系低值管理员!");
				mav.setViewName("redirect:/login.jsp");
			}else{
				session.setAttribute("userinfo", user);
				session.setAttribute("code", getUserCode(user.getUserName()));
				mav.setViewName("redirect:/tixing/shouye.do");
			}			
		}else{
			mav.addObject("message", "用户名密码错误!");
			mav.setViewName("redirect:/login.jsp");
		}
		return mav;
	}
	
	/**
	 * 退出登录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout() {
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.logout();
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		ModelAndView mav=new ModelAndView();
		mav.setViewName("redirect:/login.jsp");
		return mav;
	}
	
	@RequestMapping(value = "/changePasssword")
	public ModelAndView changePasssword(){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("system/changePassword");
		return mav;
	}
	
	@RequestMapping(value = "/passswordXiuGai")
	public String passswordXiuGai(String password){
		Subject currentUser = SecurityUtils.getSubject();
		Object obj=currentUser.getPrincipals();
		String name=obj.toString();
		User user=userManager.findByUsername(name);
		user.setPassword(password);
		userManager.cover(user);
		return "redirect:/system/logout.do";
	}
	
	@RequestMapping(value = "/miMaZH")
	public String miMaZH(String userName,String email){
		User user=userManager.getMiMaZH(userName, email);
		if(user!=null){
			final int maxNum = 36;
			int i; // 生成的随机数
			int count = 0; // 生成的密码的长度
			char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
					'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
					'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
					'8', '9' };
			StringBuffer pwd = new StringBuffer("");
			Random r = new Random();
			while (count < 8) {
				// 生成随机数，取绝对值，防止生成负数，
				i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
				if (i >= 0 && i < str.length) {
					pwd.append(str[i]);
					count++;
				}
			}
			String password=pwd.toString();
			user.setPassword(password);
			userManager.cover(user);
			//\\发送邮件
			YouJian youJian=youJianManager.get(1);
			String root=rootManager.getRoot();
			Email em=emailManager.getEmail();
			if(youJian!=null && youJian.getState()==1){
				SendMailThread st=new SendMailThread(em, root, 0, user, youJian);
				Thread t=new Thread(st);
				t.start();
			}
		}
		return "redirect:/login.jsp";
	}

	private String getUserCode(String username) {
		if (username == null || "".equals(username)) {
			return null;
		}

		String md5Str = MD5(username) + "CPECC";
		md5Str = MD5(md5Str);

		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String riQi = sdf.format(date);
		md5Str += riQi;

		return MD5(md5Str);
	}

	private String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
